package com.xinzhidi.web.task;

import com.xinzhidi.web.city.service.CityWeatherService;
import com.xinzhidi.web.netty.server.WsServer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

@Component("weatherSaveTask")
public class WeatherSaveTask {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private CityWeatherService weatherService;

    public void weatherSaveTask() {
        String lockKey = "weatherLock";
        String port = String.valueOf(WsServer.port);// 一个唯一值，可用服务器的标识或其他唯一标识

        boolean lockAcquired = redisTemplate.opsForValue().setIfAbsent(lockKey, port);
        try {
            if (lockAcquired) {
                weatherService.weatherSaveTask();
            }
        } finally {
            if (lockAcquired) {
                // 释放锁
                redisTemplate.delete(lockKey);
            }
        }

    }
}
